package com.example.person_web.core.component;

import com.example.person_web.common.WrapperResponse;
import com.example.person_web.core.entity.UserContext;
import com.example.person_web.core.entity.UserInfoDO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    // 需要跳过JWT验证的路径模式
    private static final String[] EXCLUDE_PATTERNS = {"/core/web/auth/**"};
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String requestUri = request.getRequestURI();
        boolean isExcluded = false;
        for (String pattern : EXCLUDE_PATTERNS) {
            if (pathMatcher.match(pattern, requestUri)) {
                isExcluded = true;
                break;
            }
        }

        if (isExcluded) {
            // 跳过验证，直接放行
            chain.doFilter(request, response);
            return;
        }
        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        // 从请求头中提取JWT
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try{
                jwt = authorizationHeader.substring(7);
                username = jwtUtil.extractUsername(jwt);
            } catch (Exception e){
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Credentials", "true");
                response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write(objectMapper.writeValueAsString(WrapperResponse.fail("jwt令牌无效"))); // 设置 401 状态码
                return;
            }

        }

        // 如果用户名存在且尚未认证，则进行认证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证JWT
            if (jwtUtil.validateToken(jwt, userDetails)) {
                UserInfoDO userInfoDO = new UserInfoDO();
                userInfoDO.setAccount(userDetails.getUsername());
                UserContext.setUser(userInfoDO);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将认证信息设置到SecurityContext中
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}

